#!/bin/sh

# Copyright (C) 2008 Arthur Henrique Penteado Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# On Debian systems, you can find the full text of the license in
# /usr/share/common-licenses/GPL-2

# local variables
MAIL_ADDR="arthur.furlan@gmail.com"
PROG_NAME="grade-watcher"
BASE_PATH="$HOME/.grade-watcher"

# download pages from grades.d directory and compare it with his cached version
for GRADE in $(ls "$BASE_PATH/grades.d"); do
    OLD_FILE="$BASE_PATH/cache/$GRADE.old"
    CUR_FILE="$BASE_PATH/cache/$GRADE.cur"
    URL_FILE="$BASE_PATH/grades.d/$GRADE"

    # getting files
    wget -q -i "$URL_FILE" -O "$CUR_FILE"
    if [ ! -f "$OLD_FILE" ]; then
        cp "$CUR_FILE" "$OLD_FILE"
        exit 0;
    fi

    # comparing files
    LINES=$(diff "$OLD_FILE" "$CUR_FILE" | wc -l)
    if [ "$LINES" -gt 0 ]; then
        cp "$CUR_FILE" "$OLD_FILE"

        # sending mail
        MAIL_SUBJ="$PROG_NAME: \"$GRADE\" updated"
        mail -s "$MAIL_SUBJ" "$MAIL_ADDR" < "$URL_FILE"
    fi
done
